package com.wu.store.controller;

import com.github.pagehelper.PageHelper;
import com.github.pagehelper.PageInfo;
import com.wu.store.annotation.CurrentUser;
import com.wu.store.common.util.FileUtils;
import com.wu.store.common.util.MessageEntity;
import com.wu.store.common.util.PageUtils;
import com.wu.store.common.util.RandomUtils;
import com.wu.store.dao.UserDao;
import com.wu.store.entity.PageResult;
import com.wu.store.entity.User;
import com.wu.store.service.MailService;
import com.wu.store.service.UserService;
import org.apache.commons.lang3.StringUtils;
import org.apache.shiro.SecurityUtils;
import org.apache.shiro.session.Session;
import org.apache.shiro.subject.Subject;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.StringRedisTemplate;
import org.springframework.data.redis.core.ValueOperations;
import org.springframework.util.DigestUtils;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

import java.io.Serializable;
import java.util.ArrayList;
import java.util.Date;
import java.util.List;
import java.util.concurrent.TimeUnit;

@RestController
@RequestMapping("/user")
public class UserController {

	@Autowired
	private UserDao userDao;

	@Autowired
	private UserService userService;

	@Autowired
	private MailService mailService;


	@Autowired
	private LoginController loginController;

	@Autowired
	private StringRedisTemplate stringRedisTemplate;

	@GetMapping("/info")
	public MessageEntity getUser(@CurrentUser User user) {
		User userByUid = userDao.getUserByUid(user.getId());
		MessageEntity.Builder builder = new MessageEntity.Builder();
		if (userByUid == null) {
			builder.success(false).data(null).message("获取用户信息失败");
		} else {
			builder.success(true).data(userByUid).message("获取成功");
		}
		return builder.create();
	}

	@GetMapping("/list")
	public MessageEntity getUserList(@CurrentUser User user, int page, int size, String keyword) throws Exception {
		List<User> userList = new ArrayList<>();
		PageResult pageResult = new PageResult();
		if (user.getRole() == 1) {
			PageHelper.startPage(page, size);
			userList = userDao.selectByKeyword(1, StringUtils.isEmpty(keyword) ? null : keyword);
			PageInfo<User> userPageInfo = new PageInfo<>(userList, 1);
			pageResult = PageUtils.getPageResult(userPageInfo);
		} else {
			userList.add(user);
			pageResult.setPage(page);
			pageResult.setSize(size);
			pageResult.setTotal(1);
			pageResult.setContent(userList);
		}
		return new MessageEntity.Builder().success(true).data(pageResult).message("获取成功").create();
	}

	@GetMapping("/validateIsLogged")
	public MessageEntity validateIsLogged(@CurrentUser User user) {
		Subject subject = SecurityUtils.getSubject();

		return new MessageEntity.Builder().success(subject.isAuthenticated() && user != null).data(user).create();
	}

	@RequestMapping("/isUsernameValid")
	public MessageEntity validateIsUsernameValid(String username, Long uid) throws Exception {
		User targetUser = null;
		if (uid != null) {
			targetUser = userDao.getUserByUid(uid);
		}
		boolean flag = userService.validateIsUsernameValid(username, targetUser);
		String message = "用户名可用";
		if (!flag) {
			message = "用户名已被占用";
		}
		return new MessageEntity.Builder().success(flag).message(message).create();
	}

	@RequestMapping("/register")
	public MessageEntity register(User user) throws Exception {
		userService.validateIsUsernameValid(user.getUsername(), null);
		if (StringUtils.isEmpty(user.getPassword())) {
			throw new Exception("密码必需");
		}
		String originPassword = user.getPassword();
		user.setPassword(DigestUtils.md5DigestAsHex(originPassword.getBytes()));
		// 注册的用户只能是普通用户
		user.setRole(2);
		// 注册用户默认可用
		user.setIsAvailable(1);
		user.setCreateTime(new Date());
		Integer num = userDao.addUser(user);
		boolean flag = false;
		String message = "账号注册失败";
		if (num == 1) {
			flag = true;
			message = "账号注册成功";
			loginController.login(user.getUsername(), originPassword);
		}
		return new MessageEntity.Builder().success(flag).message(message).create();
	}

	@PostMapping("/save")
	public MessageEntity updateUser(@CurrentUser User currentUser, User user) throws Exception {
		if (currentUser.getRole() != 1) {
			user.setId(currentUser.getId());
		}
		userService.validateIsUsernameValid(user.getUsername(), user);
		if (StringUtils.isNotEmpty(user.getPassword())) {
			user.setPassword(DigestUtils.md5DigestAsHex(user.getPassword().getBytes()));
		} else if (user.getId() != null) {
			User targetUser = userDao.getUserByUid(user.getId());
			user.setPassword(targetUser.getPassword());
		}
		if (StringUtils.isEmpty(user.getPassword())) {
			throw new Exception("密码必需");
		}
		if (StringUtils.isNotEmpty(user.getAvatar())){
			String avatar = FileUtils.generateFile(user.getAvatar(), user.getUsername());
			user.setAvatar(avatar);
		}

		String message = "";
		if (user.getId() == null) {
			user.setCreateTime(new Date());
			userDao.addUser(user);
			message = "新增用户成功";
		} else {
			user.setUpdateTime(new Date());
			userDao.updateUser(user);
			message = "更新用户成功";
			if (user.getId().equals(currentUser.getId())) {
				userService.updateUserCache(user);
			}
		}
		return new MessageEntity.Builder().success(true).message(message).create();
	}

	@GetMapping("/logout")
	public MessageEntity logout() {
		Subject subject = SecurityUtils.getSubject();
		Session session = subject.getSession();
		String sessionId = (String) session.getId();
		stringRedisTemplate.delete(sessionId);
		subject.logout();
		return new MessageEntity.Builder().success(true).data(true).create();
	}

	@GetMapping("/getCode")
	public MessageEntity getCode(String username) throws Exception {
		if (StringUtils.isEmpty(username)) {
			throw new Exception("用户名不能为空");
		}

		User user = userDao.getUserByUserName(username);
		if (user == null) {
			throw new Exception("用户不存在");
		} else {
			String code = RandomUtils.generateCode(4);
			mailService.send(user.getEmail(), "找回密码", code + "验证码5分钟内有效");
			ValueOperations<String, String> stringStringValueOperations = stringRedisTemplate.opsForValue();
			stringStringValueOperations.set(username, code, 5, TimeUnit.MINUTES);
			return new MessageEntity.Builder().success(true).message("验证码已发送到邮箱").create();
		}
	}

	@RequestMapping("/updatePassword")
	public MessageEntity updatePassword(String username, String code, String password) throws Exception{
		ValueOperations<String, String> stringStringValueOperations = stringRedisTemplate.opsForValue();
		String codeSaved = stringStringValueOperations.get(username);
		if(!code.equals(codeSaved)){
			throw new Exception("验证码错误");
		}
		if(StringUtils.isEmpty(password)){
			throw new Exception("密码不能为空");
		}
		String password2 = DigestUtils.md5DigestAsHex(password.getBytes());
		userDao.updatePassword(password2, username);
		return new MessageEntity.Builder().success(true).create();
//		return null;
	}
}
